﻿using RRQMSkin.MVVM;
using RRQMSocket;
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using RRQMCore.ByteManager;
using Server.Json;

namespace Server
{
	class Program
	{
		static string path;
		static string psw;

		static MyTcpService service;
		private static RRQMList<SocketClient> onLineClient=new RRQMList<SocketClient> ();
		static void Main(string[] args)
		{


			Debug.Success("你好，这里是一起听音乐管理端");


			var str = CheckClass.checkDatabase(new string[] { "server", "music", "groups" });
			path = str[0];
			psw = str[1];

			Debug.Success("请输入密码");
			while (true)
			{

				if (pswCheck())
					break;
				Debug.Error("密码错误，请重新输入：");
			}
			Debug.LogAppend(ConsoleColor.Gray, "---" + DateTime.Now.ToString() + "---" + "\r\n");
			Start();
			//下面开始启动文件服务器
			FileServer fileServer = new FileServer(configClass.FileIPHost,configClass.VerifyToken,path);

			Debug.Success("服务器已就绪，相关命令请查看文档");
			while (true)
			{




				Debug.ins(">");

				var com = Console.ReadLine();
				switch (com)
				{
					case "o":


						Debug.LogAppend(ConsoleColor.Gray, "---" + DateTime.Now.ToString() + "---" + "\r\n");
						Debug.Success("打开音乐批量上传器");

						Form4 form4 = new Form4(path);

						form4.ShowDialog();

						Debug.Success("关闭音乐批量上传器");
						break;
					case "cd":
						var serverDate = new dataTools(configClass.databaseip, configClass.databaseusername, "server", configClass.databaseport, configClass.psw);

						Debug.Log("请填写音乐路径,直接回车进行选择");
						while (true)
						{
							path = Console.ReadLine();
							if (path == "")
							{
								Debug.Log("回车");
								chooseDir();
								Debug.Success("目录选择成功，当前目录：" + path);
								fileServer.path = path;
								break;
							}
							else
							{
								if (Directory.Exists(path))
								{
									Debug.Success("目录输入成功，当前目录：" + path);
									fileServer.path = path;
									break;
								}
								else
								{
									Debug.Error("目录不存在，请重新输入");
								}

							}
						}
						serverDate.update("serverTable", new string[] { "path", path, "id", "1" });
						break;
					case "m":
						Debug.LogAppend(ConsoleColor.Gray, "---" + DateTime.Now.ToString() + "---" + "\r\n");
						Debug.Success("打开音乐管理器");

						Form2 form2 = new Form2(path);

						form2.ShowDialog();

						Debug.Success("关闭音乐管理器");
						break;
					case "t":
						
					default:
						if (com.Split(' ').Length > 1 && com.Split(' ')[0] == "say")
						{
							foreach (var item in onLineClient)
							{
							//	var msg = JsonHelper.server_serialization("管理：" + com);

								service.Send(item.ID, Encoding.UTF8.GetBytes("你好"));
							}
							break;
						}
						else 
						{

						}
						Debug.Error("未知命令");
						break;
				}


			}
		}
		public static void Start()
		{
			service = new MyTcpService();

			service.ClientConnected += (object sender, MesEventArgs e) =>
			{
				//有客户端连接
				//sender对象为MySocketClient类型
				MySocketClient client = (MySocketClient)sender;

				service.Send(client.ID, Encoding.UTF8.GetBytes(""));
				returnValue(client.ID, "uinf", "欢迎你", new string[] { client.ID });
				onLineClient.Add(client);
			};

			service.ClientDisconnected += (object sender, MesEventArgs e) =>
			{
				//有客户端断开连接
				//sender对象为MySocketClient类型
				MySocketClient client = (MySocketClient)sender;

				onLineClient.Remove(client);
			};
			

			//声明配置
			var config = new TcpServiceConfig();
			config.ListenIPHosts = new IPHost[] { new IPHost("127.0.0.1:33005"), new IPHost(7790) };//同时监听两个地址
			config.BufferLength = 1024 * 64;//缓存池容量
			config.BytePoolMaxSize = 512 * 1024 * 1024;//单个线程内存池容量
			config.BytePoolMaxBlockSize = 20 * 1024 * 1024;//单个线程内存块限制
			config.Logger = new Log();//日志记录器，可以自行实现ILog接口。
			config.ServerName = "RRQMService";//服务名称
			config.SeparateThreadReceive = false;//独立线程接收，当为true时可能会发生内存池暴涨的情况
			config.ThreadCount = 5;//多线程数量，当SeparateThreadReceive为false时，该值只决定BytePool的数量。
			config.Backlog = 30;
			config.ClearInterval = 6000 * 1000;//60秒无数据交互会清理客户端
			config.ClearType = ClearType.Receive | ClearType.Send;//清理统计
			config.MaxCount = 10000;//最大连接数


			//载入配置                                                       
			service.Setup(config);

			//启动
			service.Start();
		}
		private static void Service_Received(SimpleSocketClient arg1, ByteBlock arg2, object arg3)
		{

			string msg = Encoding.UTF8.GetString(arg2.Buffer, 0, (int)arg2.Length);
		}
			private static void Service_ClientDisconnected(object sender, MesEventArgs e)
		{

			SimpleSocketClient client = (SimpleSocketClient)sender;
		}
		private static void Service_ClientConnected(object sender, MesEventArgs e)
		{

			SimpleSocketClient client = (SimpleSocketClient)sender;

		}
		private static void Service_CreatSocketCliect(SimpleSocketClient arg1, CreateOption arg2)
		{

		}
		static void returnValue(string uid,string tab,string ret)

		{
			
			string sid = "server";

			var json = JsonHelper.ServerRequest_serialization(sid,tab, ret);
			service.Send(uid, Encoding.UTF8.GetBytes(json));
		}

		static void returnValue(string uid, string sid,string tab, string ret)
		{
			var json = JsonHelper.ServerRequest_serialization(sid, tab, ret);
			service.Send(uid, Encoding.UTF8.GetBytes(json));
		}
		static void returnValue(string uid, string _uid, string sid ,string tab, string ret)
		{
			var json = JsonHelper.ServerRequest_serialization(sid, tab, ret);
			service.Send(uid, Encoding.UTF8.GetBytes(json));
		}
		static void returnValue(string uid, string sid, string tab, string ret,string [] arr)
		{
			var json = JsonHelper.ServerRequest_serialization(sid, tab, ret,arr);
			service.Send(uid, Encoding.UTF8.GetBytes(json));
		}
		static void returnValue(string uid, string tab, string ret, string[] arr)
		{
			string sid = "server";

			var json = JsonHelper.ServerRequest_serialization(sid, tab, ret, arr);
			service.Send(uid, Encoding.UTF8.GetBytes(json));
		}


		static void chooseDir()
		{
			Thread t = new Thread((ThreadStart)(() =>
			{
				FolderBrowserDialog dlg = new FolderBrowserDialog();

				if (dlg.ShowDialog() == DialogResult.OK)
				{
					path = dlg.SelectedPath.ToString();
				}

			}));
			t.SetApartmentState(ApartmentState.STA);
			t.Start();
			t.Join();

		}
		static bool pswCheck()
		{
			if (Debug.password() == psw)
				return true;
			return false;
		}
	}
}
